/**
 * All rights Reserved, Designed By 信鸥科技
 * project : committee
 * Created by youquer on 17/10/25.
 * 注意：本内容仅限于信鸥科技有限公司内部传阅，禁止外泄以及用于其他的商业目的
 * Description:
 *
 */
import { postList, postInfo, postUpdate, postAdd, postDelete, postAllAppList, postAppRole} from '@/services/powers/user';
import { query as queryUsers, queryCurrent } from '@/services/user';

import { message } from 'antd';
import queryString from 'query-string';
import { routerRedux } from 'dva/router';
import Cookies from 'universal-cookie';
const cookie = new Cookies();

export default {
  namespace: 'user',
  state: {
    type: "user",
    currentUser: {},

    id: '', //id
    //分页
    page: 1, //当前页
    pageSize: 10, //每页条数
    total: 0, //总页数
    //列表页-添加页提交按钮loading
    loading: false,//添加页确定按钮loading
    dataList: [], //列表页数据数据
    isUpdate: 0, //是否是修改页: 0:添加页, 1:修改页
    isMenu: false, //是否是菜单

    isLawyer: 0, //1-律师, 0-非律师

    //搜索部分
    //搜索字段
    values:"",
    advanceTails:{}, //高级搜索内容
    searchValue:"", //普通搜索内容
    selectValue:"real_name", //普通搜索
    isAdvance:false, //高级搜索暂开
    expand: false, //是否有高级搜索
    searchExpand: false, //是否存在搜索
    commonSelectData:[
      {
        value:"real_name",
        text:"真实姓名"
      },
    ], //普通搜索内容,

    //树
    roleIdsTree:[], //角色树
    roleIds: [], //角色树值
    appTree: [], //应用树
    appIds: [],  //应用树值
    //所有已获得的 应用的角色
    selectApp: [],
    realName: '',
    account: '',

    //tabs标签
    key: '1', //1: 可用:标签一, 2:不可用:标签二

  },

  reducers: {

    //赋值数据
    setState(state, action){
      return {...state, ...action.payload};
    },
    //分页act
    changePage(state, action){
      return {...state, page: action.page, pageSize: action.pageSize}
    },
    //搜索
    searchData(state,action){
      if (action.key != undefined){
        state.advanceTails[action.key] = action.value;
      }

      if (action.selectValue != undefined){
        state.selectValue = action.selectValue;
      }

      //当点击搜索的时候调起接口
      if (action.searchValue != undefined){
        state.searchValue = action.searchValue;
      }
      return{...state,expand:action.expand};
    },
    //搜索重置
    advanceReset(state,action){
      return {...state,...action.payload,loading: false}
    },
    //添加成功
    addSuccess(state, action){
      return {...state,...action.payload, loading: false};
    },
    //选择姓名回调
    clickNameSuccess(state, action){
      return{...state, ...action.payload};
    },
    //添加页获取数据
    changeState(state, action){
      var t = {};
      t[action.key] = action.value;
      return {...state, ...t};
    },
    //提交按钮
    submit(state,action){
      return {...state,loading:action.loading}
    },
    //提交成功
    querySuccess(state, action){

      return {...state,...action.payload, loading: false};
    },
    //清楚数据
    clearData(state){
      return {...state,
        isMenu: false,
        name: '',
        parentId: '',
        url:'',
        isEnable:'',
        sort: '',
        roleIdsTree:[],
        roleIds: [],
        appTree: [],
        appIds: [],
        selectApp: [],
        realName: '',
        account: '',
        isLawyer: 0, //1-律师, 0-非律师
      };
    },
    //
    save(state, action) {
      return {
        ...state,
        list: action.payload,
      };
    },
    saveCurrentUser(state, action) {
      return {
        ...state,
        currentUser: action.payload || {},
      };
    },
    changeNotifyCount(state, action) {
      return {
        ...state,
        currentUser: {
          ...state.currentUser,
          notifyCount: action.payload,
        },
      };
    },
  },

  subscriptions: {
    //路由启动时,调用  也就是初始化页面
    setup({ dispatch, history }) {
      history.listen(location => {
        if (location.pathname === '/permissions/userAdd'){ //跳到
          //清空数据
          dispatch({
            type: 'clearData',
          });
          dispatch({
            type: 'toAdd',
          });
          dispatch({
            type: 'setState',
            payload: {isUpdate:0}
          })
        } else if (location.pathname === '/permissions/userEdit'){ //跳到修改页
          var search = queryString.parse(location.search);
          //清空数据
          dispatch({
            type: 'clearData',
          });
          dispatch({
            type: 'toAdd',
          });
          //获取详情
          dispatch({
            type: 'getInfo',
            payload: {id: search.id},
          });
          dispatch({
            type: 'setState',
            payload: {isUpdate: 1}
          })
        }  else if (location.pathname === '/permissions/user'){ //列表页
          //调用列表页方法
          dispatch({
            type: 'dateList',
          });
        }
      });
    }
  },

  effects:{
    //列表页,分页,搜索页
    *dateList({payload}, { call, put ,select}) {
      var dates = yield select(state => state.user);
      var params = {};
      params["pageSize"] = dates.pageSize;
      params["selectValue"] = dates.selectValue;
      params["searchValue"] = dates.searchValue;
      if (payload){
        params["page"] = payload;
      } else {
        params["page"] = dates.page;
      }
      const data = yield call(postList, params);
      if (data) {
        if (data.body && data.recode == 200){
          yield put({
            type: 'setState',
            payload: {
              dataList: data.body.dataList,
              total: data.body.total,
            }
          });
        } else if (data.recode == 9000){
          message.error("您的权限不足");
        } else if (data.recode == 1001){
          yield put(routerRedux.push("/user/login"));
        } else {
          message.error('网络请求失败!');
        }
      } else {
        message.error("网络请求失败");
      }
    },
    //获取详情信息
    *getInfo({payload}, { call, put ,select}){
      const data = yield call(postInfo, payload);
      if (data){
        if (data.recode == 200){
          if (data.body.user){
            var roleAppList = data.body.user.roleAppList;
            var params = data.body.user; //用户基本信息
            if (roleAppList){
              var appIdSet = new Set();
              for (var i = 0; i < roleAppList.length; i++){
                appIdSet.add(roleAppList[i].appId);
              }
              var appId = [];
              for (var x of appIdSet) { // 遍历Set
                var t = {};
                var roleArray = [];
                for (var j = 0; j < roleAppList.length; j++){
                  if (roleAppList[j].appId == x){
                    roleArray.push(roleAppList[j].id + "");
                    if (roleAppList[j].appId == 1 && roleAppList[j].id == 2){
                      yield put({
                        type: "setState",
                        payload: {isLawyer: 1},
                      });
                    }
                  }
                }

                t[x + "key"] = roleArray;
                yield put({
                  type: "setState",
                  payload: t,
                });

                yield put({
                  type: "getAppRole",
                  payload: x,
                });
                appId.push(x);
              }
            }
            params["appIds"] = appId;
            yield put({
              type: 'setState',
              payload: params,
            })
          }
        } else if (data.recode == 9000){
          message.error("您的权限不足");
        } else if (data.recode == 1001){
          yield put(routerRedux.push("/user/login"));
        } else {
          message.error('网络请求失败!');
        }
      } else {
        message.error("网络请求失败");
      }
    },
    //删除
    *delete({payload}, {call, put}){
      const dic = {id: payload};
      const data = yield call(postDelete,dic);
      if (data){
        if (data.recode == 200){
          message.success("删除该条信息成功");
          yield put({
            type: 'dateList',
          });
        } else if (data.recode == 9000){
          message.error("您的权限不足");
        } else if (data.recode == 1001){
          yield put(routerRedux.push("/user/login"));
        } else {
          message.error('网络请求失败!');
        }
      } else {
        message.error("网络请求失败!>_<");
      }
    },
    //添加修改网络请求
    *update({payload}, {call, put, select}) {
      var user = yield select(state => state.user);
      var roleIds = [];
      if (payload.appIds){
        for (var i = 0; i < payload.appIds.length; i++){
          var key = payload.appIds[i] + "key";
          var array = user[key];
          if (array){
            if (i == 0){
              roleIds = array;
            } else {
              roleIds = roleIds.concat(array);
            }
          }
        }
      }
      payload["roleIds"] = roleIds;
      if (payload.realName && payload.account){
        payload.id = yield select(state => state.user.id);
        const data = yield call(postUpdate,{...payload});
        if (data) {
          if (data.recode == 200){
            message.success('提交成功');
            yield put({
              type:'addSuccess',
              payload:{
                loading: false,
              }
            });
            yield put(routerRedux.push("/permissions/user"));
          } else if (data.recode == 9000){
            message.error("您的权限不足");
          } else if (data.recode == 1001){
            yield put(routerRedux.push("/user/login"));
          } else {
            message.error('网络请求失败,请重新提交');
            yield put({
              type:'submit',
              loading: false
            })
          }
        } else {
          message.error("网络求情失败");
          yield put({
            type:'submit',
            loading: false
          })
        }
      }else {
        message.warn('所有信息均为必填信息');
        yield put({
          type:'submit',
          loading: false
        })
      }
    },
    //添加接口
    *add({payload}, {call, put, select}) {
      var user = yield select(state => state.user);
      var roleIds = [];
      if (payload.appIds){
        for (var i = 0; i < payload.appIds.length; i++){
          var key = payload.appIds[i] + "key";
          var array = user[key];
          if (array){
            if (i == 0){
              roleIds = array;
            } else {
              roleIds = roleIds.concat(array);
            }
          }
        }
      }
      payload["roleIds"] = roleIds;
      if (payload.realName && payload.account && payload.appIds.length > 0){
        const data = yield call(postAdd,{...payload});
        if (data) {
          if (data.recode == 200){
            message.success('提交成功');
            yield put({
              type:'addSuccess',
              payload:{
                loading: false,
              }
            });
            yield put(routerRedux.push("/permissions/user"));
          } else if (data.recode == 9000){
            message.error("您的权限不足");
          } else if (data.recode == 1001){
            yield put(routerRedux.push("/user/login"));
          } else {
            message.error(data.remsg);
            yield put({
              type:'submit',
              loading: false
            })
          }
        } else {
          message.error("网络请求失败");
          yield put({
            type:'submit',
            loading: false
          })
        }
      }else {
        message.warn('所有信息均为必填信息');
        yield put({
          type:'submit',
          loading: false
        })
      }
    },
    //获取应用数
    *toAdd({payload}, { call, put ,select}){
      var params = {
        page: 1,
        pageSize: 1000,
      };
      const data = yield call(postAllAppList, params);
      if (data){
        if (data.recode == 200){
          if (data.body.dataList){
            var appTree = [];
            for (var i = 0; i < data.body.dataList.length; i++){
              var item = data.body.dataList[i];
              var param = {
                title: item.name,
                value: item.id + "",
              };
              appTree.push(
                param
              )
            }
            yield put({
              type: 'setState',
              payload: {appTree: appTree},
            })
          }
        } else if (data.recode == 9000){
          message.error("您的权限不足");
        } else if (data.recode == 1001){
          yield put(routerRedux.push("/user/login"));
        } else {
          message.error('网络请求失败!');
        }
      } else {
        message.error("网络请求失败");
      }
    },
    //根据role获取权限
    *getAppRole({payload}, { call, put ,select}){
      var dates = yield select(state => state.user);
      var params = {
        id : payload
      };
      const data = yield call(postAppRole, params);
      if (data){
        if (data.recode == 200){
          var roleTree = [];
          for (var i = 0; i < data.body.dataList.length; i++){
            var item = data.body.dataList[i];
            var param = {
              title: item.name,
              value: item.id + "",
            };
            roleTree.push(
              param
            )
          }
          var t = {};
          t[payload] = roleTree;
          yield put({
            type: 'setState',
            payload: t,
          })
        } else if (data.recode == 9000){
          message.error("您的权限不足");
        } else if (data.recode == 1001){
          yield put(routerRedux.push("/user/login"));
        } else {
          message.error('网络请求失败!');
        }
      } else {
        message.error("网络请求失败");
      }
    },
    //选择树回调
    *moreTreeCallBack({payload}, { call, put ,select}){
      //所有已获得的应用的角色
      //selectApp: [];
      var dates = yield select(state => state.user);
      var selectApp = dates.selectApp;
      for (var i = 0; i < payload.length; i++){
        var isCanUp = 1;
        for (var j = 0; j < selectApp.length; j++){
          if (payload[i] == selectApp[j]) {
            isCanUp = 0;
            break;
          } else {
            isCanUp = 1;
          }
        }
        if (isCanUp == 1){
          var t = {};
          t[payload[i] + "key"] = [],
            yield put({
              type: "setState",
              payload: t
            });
          yield put({
            type: "getAppRole",
            payload: payload[i]
          })
        }
      }
      //
      yield put({
        type: "setState",
        payload: {selectApp: payload}
      })
    },
    //角色树
    *roleMoreTreeCallBack({payload}, { call, put ,select}){
      var dates = yield select(state => state.user);
      var roleIds = dates["1key"];
      if (dates.isLawyer){
        var isHave = 0
        for (var i = 0; i < payload.length; i++){
          if ("2" == payload[i]){
            isHave = 1;
          }
        }
        if (!isHave){
          roleIds.push(
            "2"
          );
          var t = {};
          t["1key"] = roleIds;
          yield put({
            type: 'save',
            payload: t
          })
        }
      }
    },
    //用户信息
    *fetchCurrent(_, { call, put }) {
      console.log(cookie.get('name'));
      let response = {
        name: cookie.get('name')
      };
      yield put({
        type: 'saveCurrentUser',
        payload: response,
      });
    },
  },
}
